import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';

export enum MarkType {
  DIRTY = 'dirty',
  PRISTINE = 'pristine',
}

export class FormUtils {
  static markAs(control: AbstractControl, markType: MarkType) {
    if (control instanceof FormControl && !control.dirty) {
      control.markAsDirty();
      control.updateValueAndValidity();
    } else if (control instanceof FormArray) {
      control.controls.forEach(item => {
        this.markAs(item, markType);
      });
    } else if (control instanceof FormGroup) {
      Object.keys(control.controls).forEach(key => {
        this.markAs(control.controls[key], markType);
      });
    }
  }

  static verifyState(control: AbstractControl) {
    FormUtils.markAs(control, MarkType.DIRTY);
  }

  static resetState(control: AbstractControl) {
    FormUtils.markAs(control, MarkType.PRISTINE);
  }
}
